package edu.poly.cs9223.assginment1;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.services.cloudwatch.AmazonCloudWatchClient;
import com.amazonaws.services.cloudwatch.model.Dimension;
import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsRequest;
import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsResult;

/**
 * Check CloudWatch metrics periodically
 * 
 * @author Kevin Zhao
 * 
 */
public class CloudWatchChecker implements Runnable {
	Logger logger = LoggerFactory.getLogger(CloudWatchChecker.class);
	public int checking_waiting_period = Main.IDLE_THRESHOLD_PERIOD*1000;// default value is 60seconds
	Date startTime = new Date();
	Date endTime = null;
	User user;
	private AmazonCloudWatchClient amazonCloudWatchClient = null;

	public CloudWatchChecker(AWSCredentials credentials,User user) {
		super();
		this.user = user;
		amazonCloudWatchClient = new AmazonCloudWatchClient(credentials);
	}

	public void run()  {
		logger.debug("obtaining cloudwatch metrics.");
		while (true) {
			// waiting
			logger.debug(".");
			try {
				Thread.sleep(checking_waiting_period);
				endTime = new Date();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// get cloud watch metrics
			Dimension dimension = new Dimension();
			dimension.setName("AutoScalingGroupName");
			dimension.setValue(user.getAutoScalingGroupName());
			
			GetMetricStatisticsRequest getMetricStatisticsRequest = new GetMetricStatisticsRequest();
			getMetricStatisticsRequest.withMetricName("CPUUtilization").withDimensions(dimension)
					.withStartTime(startTime).withEndTime(endTime)
					.withPeriod(Main.SCALE_UP_DOWN_THRESHOLD_PERIOD).withStatistics("Average")
					.withNamespace("AWS/EC2");
			
			GetMetricStatisticsResult cwResult = amazonCloudWatchClient
					.getMetricStatistics(getMetricStatisticsRequest);
			
			//forward result to Main
			try {
				Main.onDemandCheck(user,cwResult);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}

}
